package com.lujieni.nio.c2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

public class WriteServer {

    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8081));
        ssc.configureBlocking(false);
        ssc.register(selector, SelectionKey.OP_ACCEPT); // 注册监听的事件

        while (true){
          selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey sk = iterator.next();
                iterator.remove();

                if(sk.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < 50000000; i++) {
                        sb.append("a");
                    }

                    ByteBuffer bb = Charset.defaultCharset().encode(sb.toString());
                    int writeCount = sc.write(bb);
                    System.out.println(writeCount);
                    if(bb.hasRemaining()){
                        sc.register(selector, SelectionKey.OP_READ + SelectionKey.OP_WRITE, bb);
                    }
                }else if(sk.isWritable()){
                    SocketChannel channel = (SocketChannel)sk.channel();
                    ByteBuffer bb = (ByteBuffer)sk.attachment();
                    int writeCount = channel.write(bb);
                    System.out.println(writeCount);
                    if(!bb.hasRemaining()){
                        sk.attach(null); // 解绑ByteBuffer
                        sk.interestOps(sk.interestOps() - SelectionKey.OP_WRITE); //不需要关注Write事件
                    }
                }

            }
        }

    }
}
